package com.jn.tendemo.viewModel;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;


import com.jn.tendemo.entity.PetEntity;
import com.jn.tendemo.repository.PetRepository;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class PetListModel extends ViewModel {
    private PetRepository petRepository ;
    private MutableLiveData<PetEntity> liveData = new MutableLiveData<>() ;

    public PetListModel(){
        petRepository = new PetRepository() ;
    }

    public void getData(String name , int type){
        Log.d("搜索内容", "运行到此处");
        if (name == null && type < 5){
            petRepository.getData(type).subscribe(new Observer<PetEntity>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                }

                @Override
                public void onNext(@NonNull PetEntity petEntity) {
                    Log.d("返回状态码", String.valueOf(petEntity.getCode()));
                    if (petEntity.getCode() == 200){
                        liveData.postValue(petEntity);
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    Log.d("返回状态码", String.valueOf(e.getMessage()));
                }

                @Override
                public void onComplete() {
                }
            });
        }else {
            petRepository.getData2(name).subscribe(new Observer<PetEntity>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull PetEntity petEntity) {
                    Log.d("返回状态码", String.valueOf(petEntity.getCode()));
                    if (petEntity.getCode() == 200){
                        liveData.postValue(petEntity);
                    }else {
                        liveData.postValue(null);
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }

    }

    public MutableLiveData<PetEntity> getLiveData(){
        Log.d("返回数据长度", liveData.toString());
        return liveData ;
    }
}
